<?php
class Hotel extends AppModel {
    public $name         = 'Hotel';
    public $hasMany = array(
        'Rate' => array(
            'className'   => 'Rate',
            'fields'      => array('from', 'to', 'description', 'd_1', 'd_2', 'd_3', 'd_4', 'e_1', 'e_2', 'e_3', 'e_4'),
            'dependent'   => true
            //'finderQuery' => 'SELECT Rate.`hotel_id`, Rate.`room_type_id`, Rate.`rate_code_id`, Rate.`from` FROM `rates` AS Rate INNER JOIN `hotels` AS Hotel ON Hotel.`id` = Rate.`hotel_id`'
        )
    );

    public function hotelList ($params) {
        $page = $params['page'];
        $cond = 'h.`status`="A" ';

        if ($params['query'] && $params['qtype']) {
            $cond .= 'AND h.`'.$params['qtype'].'` LIKE "%'.$params['query'].'%" ';
        }

        $sql = 'SELECT COUNT(*) AS total FROM `hotels` AS h ' .
               'WHERE '.$cond;
        $ttl = $this->query($sql);

        $total = (count($ttl) == 0) ? 0 : $ttl[0][0]['total'];
        if ($total == 0) {
            return array(
                'page'  => 1,
                'total' => 0,
                'rows'  => array()
            );
        }

        $rpp   = isset($params['rp']) ? $params['rp'] : 10;
        $start = (($page-1) * $rpp);
        $sort  = empty($params['sortname']) ? 'id' : $params['sortname'];
        $ord   = (empty($params['sortorder']) || $params['sortorder'] == 'asc') ? 'ASC' : 'DESC';
        $sql   = 'SELECT h.* FROM `hotels` AS h ' .
                 'WHERE '.$cond .
                 'ORDER BY h.`'.$sort.'` '.$ord.' ' .
                 'LIMIT '.$start.', '.$rpp;
        $data = $this->query($sql);
        $rec  = array();

        if (count($data) == 0) {
            return array(
                'page'  => 1,
                'total' => 0,
                'rows'  => array()
            );
        }

        foreach ($data as $rs) {
            $id = $rs['h']['id'];

            $created  = $this->serverToClientTime($rs['h']['created'], 'd/m/Y H:i a');
            $modified = $this->serverToClientTime($rs['h']['modified'], 'd/m/Y H:i a');
            $actions  = '<div class="selectRecord" onclick="hotel.select('.$id.');"></div>' .
                        '<div class="editRecord" onclick="hotel.edit('.$id.');"></div>';

            $cell = array(
                $id, $rs['h']['name'], $rs['h']['street'], $rs['h']['city'], $rs['h']['state'], $rs['h']['zip_code'],
                $rs['h']['phone'], $rs['h']['fax'], $rs['h']['email'], $created, $modified, $actions
            );

            $rec[] = array(
                'id'   => $id,
                'cell' => $cell
            );
        }

        return array(
            'page'  => $page,
            'total' => $total,
            'rows'  => $rec
        );
    } // hotelList
} // Hotel
?>